<script setup lang="ts">
import type { EChartsOption } from 'echarts'
import echarts from '@/plugin/echarts'
import { LinesChart } from 'echarts/charts'
import { EffectScatterChart } from 'echarts/charts'
import { ToolboxComponent, DataZoomSliderComponent } from 'echarts/components'
import { debounce } from 'lodash-es'
import 'echarts-wordcloud'
import { propTypes } from '@/utils/propTypes'
import { isString } from '@/utils/is'
import yangze_map from '@/assets/geo/yangze_map'
echarts.registerMap('长三角', yangze_map as any)
echarts.use([ToolboxComponent, DataZoomSliderComponent, LinesChart, EffectScatterChart])

const props = defineProps({
  options: {
    type: Object as PropType<EChartsOption>,
    required: true
  },
  onClick: {
    type: Function as PropType<(params: any) => void>,
    default: () => {}
  },
  width: propTypes.oneOfType([Number, String]).def('100%'),
  height: propTypes.oneOfType([Number, String]).def('500px')
})

const options = computed(() => {
  return Object.assign(props.options)
})

const elRef = ref<ElRef>()

let echartRef: Nullable<echarts.ECharts> = null

const contentEl = ref<Element>()

const styles = computed(() => {
  const width = isString(props.width) ? props.width : `${props.width}px`
  const height = isString(props.height) ? props.height : `${props.height}px`

  return {
    width,
    height
  }
})

const initChart = () => {
  if (unref(elRef) && props.options) {
    echartRef = echarts.init(unref(elRef) as HTMLElement)
    echartRef?.setOption(unref(options))
    echartRef?.on('click', props.onClick)
  }
}

watch(
  () => options.value,
  (options) => {
    if (echartRef) {
      echartRef?.setOption(options, true)
    }
  },
  {
    deep: true
  }
)

const resizeHandler = debounce(() => {
  if (echartRef) {
    echartRef.resize()
  }
}, 100)

const contentResizeHandler = async (e: TransitionEvent) => {
  if (e.propertyName === 'width') {
    resizeHandler()
  }
}

onMounted(() => {
  setTimeout(() => {
    initChart()
  }, 0)

  window.addEventListener('resize', resizeHandler)

  contentEl.value = document.getElementsByClassName(`layout-content`)[0]
  unref(contentEl) &&
    (unref(contentEl) as Element).addEventListener('transitionend', contentResizeHandler)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeHandler)
  unref(contentEl) &&
    (unref(contentEl) as Element).removeEventListener('transitionend', contentResizeHandler)
})

onActivated(() => {
  if (echartRef) {
    echartRef.resize()
  }
})
</script>

<template>
  <div ref="elRef" :class="[$attrs.class]" :style="styles"></div>
</template>
